<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document Encryption Setup</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
      background-color: #f4f4f4;
    }

    form {
      width: 80%;
      max-width: 800px;
      background: white;
      padding: 2em;
      border-radius: 10px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }

    h2 {
      text-align: center;
      margin-bottom: 1em;
    }

    label {
      display: block;
      margin-top: 1em;
    }

    textarea,
    input[type="text"],
    input[type="password"] {
      width: 100%;
      padding: .5em;
      margin-top: .5em;
      border: 1px solid #ddd;
      border-radius: 5px;
    }

    button {
      display: block;
      width: 100%;
      padding: 1em;
      margin-top: 1em;
      background: #007BFF;
      color: white;
      border: none;
      border-radius: 5px;
      cursor: pointer;
    }

    button:hover {
      background: #0056b3;
    }

    .fileList {
      margin-top: 1em;
    }

    .fileList table {
      width: 100%;
      border-collapse: collapse;
      margin-bottom: 1em;
    }

    .fileList th, .fileList td {
      padding: 8px;
      text-align: left;
      border: none;
    }

    .fileList th {
      background-color: #f2f2f2;
      border-bottom: none;
    }

    .fileList tr:last-child td {
      border-bottom: none;
    }

    .fileList td:first-child {
      border-left: none;
    }

    .fileList td:last-child {
      border-right: none;
    }

    .fileList button {
      padding: .5em;
      margin-top: 0;
      border-radius: 5px;
      background: #ff5c5c;
      color: white;
      border: none;
      cursor: pointer;
    }

    .fileList button:hover {
      background: #e64a4a;
    }

    .fileList .fileEntry:last-child {
      margin-bottom: 0;
    }
  </style>
</head>
<body>
<form id="encryptionForm">
  <h2>加密工具设置</h2>

  <div class="fileList">
    <table>
      <thead>
      <tr>
        <th>文件地址</th>
        <th>文件名称</th>
        <th>文件类型</th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr class="fileEntry">
        <td><input type="text" name="filePath1" placeholder="File Path" value="c:/test.pdf"></td>
        <td><input type="text" name="fileName1" placeholder="File Name" value="test.pdf"></td>
        <td><input type="text" name="fileType1" placeholder="File Type" value="pdf"></td>
        <td>
          <button type="button" onclick="removeFileEntry(this)">Remove</button>
        </td>
      </tr>
      </tbody>
    </table>
  </div>

  <button type="button" onclick="addFileEntry()">添加文件</button>

  <label for="zipName">加密文件压缩包名称:</label>
  <input type="text" id="zipName" name="zipName" value="test.zip">

  <label for="zipName"> 加密文件输出地址:</label>
  <input type="text" id="encryptedFileExportPath" name="encryptedFileExportPath" value="C:/demo/">

  <h3>CA互认共享组件配置</h3>
  <label for="tradingSystemCode">交易系统编码:</label>
  <input type="text" id="tradingSystemCode" name="tradingSystemCode" value="C1100005553">

  <label for="caServiceUrl">CA Service Url (CA互认共享组件服务地址):</label>
  <input type="text" id="caServiceUrl" name="caServiceUrl" value="http://36.142.16.73:8992">

  <label for="clientId">Client ID (客户端ID):</label>
  <input type="text" id="clientId" name="clientId" value="trading_system">

  <label for="clientSecret">Client Secret (客户端密钥):</label>
  <input type="text" id="clientSecret" name="clientSecret" value="DA960F1BC072486BBC3C04023C0743A5">

  <label for="signatureSecret">Signature Secret(签名密钥):</label>
  <input type="text" id="signatureSecret" name="signatureSecret" value="54ECD15D6E0440E3AF79AB3D3DACC6F8">

  <button type="button" onclick="onStart()">启动工具</button>
</form>

<script>
  let socket
  let isConnect = false
  let isConnecting = false
  let socketData

  function connectWebSocket() {
    isConnecting = true
    socket = new WebSocket('ws://localhost:12345')
    socket.binaryType = 'JSON'
    socket.onopen = (event) => {
      isConnect = true
      console.log('WebSocket is open now.')
    }

    socket.onmessage = (event) => {
      if (socketData) {
        socket.send(socketData)
        socketData = undefined
      }
      console.log('Received data from server: ', event.data)
    }

    socket.onclose = (event) => {
      isConnect = false
      isConnecting = false
      console.log('WebSocket is onclose now.')
    }

    socket.onerror = (error) => {
      isConnect = false
      connectWebSocket()
      console.error('WebSocket Error: ', error)
    }
  }

  function addFileEntry() {
    const fileList = document.querySelector('.fileList tbody')
    const nextIndex = fileList.childElementCount + 1;
    const entryTemplate = `
        <tr class="fileEntry">
            <td><input type="text" name="filePath${nextIndex}" placeholder="File Path"></td>
            <td><input type="text" name="fileName${nextIndex}" placeholder="File Name"></td>
            <td><input type="text" name="fileType${nextIndex}" placeholder="File Type"></td>
            <td><button type="button" onclick="removeFileEntry(this)">Remove</button></td>
        </tr>
    `
    fileList.insertAdjacentHTML('beforeend', entryTemplate);
  }

  function removeFileEntry(button) {
    const entry = button.closest('tr')
    entry.parentNode.removeChild(entry)
  }

  function onStart() {
    const formData = new FormData(document.getElementById('encryptionForm'))
    const data = {
      CAShareUseScene: '01',
      keyParameter: {
        awaitingEncryptionFileList: [],
        encryptedFileZipName: formData.get('zipName'),
        encryptedFileExportPath: formData.get('encryptedFileExportPath'),
        caShareComponentConfig: {
          tradingSystemCode: formData.get('tradingSystemCode'),
          caShareComponentServiceUrl: formData.get('caServiceUrl'),
          clientId: formData.get('clientId'),
          clientSecret: formData.get('clientSecret'),
          signatureSecret: formData.get('signatureSecret')
        }
      }
    }

    for (const [key, value] of formData.entries()) {
      if (key.startsWith('filePath')) {
        const entryKey = key.replace('filePath', '')
        data.keyParameter.awaitingEncryptionFileList.push({
          awaitingEncryptionFilePath: value,
          awaitingEncryptionFileName: formData.get(`fileName${entryKey}`),
          fileType: formData.get(`fileType${entryKey}`)
        })
      }
    }
    socketData = JSON.stringify(data)
    console.log(socketData)
    window.location.href = 'CAShareDetectInstallTool://websocket?flag=1'
    if (!isConnect) {
      if (!isConnecting) {
        connectWebSocket()
      }
    } else {
      socket.send(socketData)
      socketData = undefined
    }
  }
</script>
</body>
</html>
